package com.neusoft.neps.controller;

import com.neusoft.neps.entity.user;
import com.neusoft.neps.method.UsersIO;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.*;

public class LogInController {


    @FXML
    private TextField phoneField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button registerButton;
    @FXML
    private Button loginButton;



    @FXML
    private void handleLogin() {
        String phone = phoneField.getText();
        String password = passwordField.getText();
        Map<String,user> users = new HashMap<>();
        try {
             users = UsersIO.readUsers("users.txt");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (phone.isEmpty() || password.isEmpty()) {
            showAlert("登录失败", "请输入手机号和密码");
            return;
        }
        else if(!users.containsKey(phone) || !Objects.equals(password,users.get(phone).getPassword())){
            showAlert("登录失败", "用户名或密码错误");
            return;
        }
        user nowUser = users.get(phone);
        try {
            File file = new File("src/com/neusoft/neps/data/nowUser.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
                oos.writeObject(nowUser);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            // 登录成功后跳转到网格选择页面
            navigateTo("../view/SelectGridView.fxml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleRegister() {
        try {
            navigateTo("../view/RegisterView.fxml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void navigateTo(String fxmlPath) throws Exception {
        FXMLLoader fxmlLoader = new FXMLLoader();
        Stage stage = (Stage) loginButton.getScene().getWindow();
        System.out.println(fxmlPath);
        URL url = getClass().getResource(fxmlPath);
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root, 600, 400);
        stage.setScene(scene);
        stage.show();
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
